//
//  JKTimerControl.m
//  MRC_Playground
//
//  Created by Developer on 2022/3/31.
//

#import "JKTimerControl.h"

@implementation JKTimerControl{
    id <JKTimerControlDelegate>_delegate;
    NSTimer *_timer;
}

- (void)dealloc{
    NSLog(@"JKTimerControl dealloc");
    [super dealloc];
}

#pragma mark - Private
- (void)actionTimeUp:(NSTimer *)timer{
    if (_delegate && [_delegate respondsToSelector:@selector(jk_timerCallback)]) {
        [_delegate jk_timerCallback];
        NSDictionary *userInfo = timer.userInfo;
        BOOL repeat = [userInfo[@"repeat"] boolValue];
        if (!repeat) {
            [self stopTimer];
        }
    }else{
        [self stopTimer];
    }
}

- (void)stopTimer{
    if (_timer) {
        [_timer invalidate];
        [_timer release]; _timer = nil;
    }
}

#pragma mark - Public
- (void)creatTimerWithDelegate:(id<JKTimerControlDelegate>)delegate{
    if (!delegate) {
        return;
    }
    _delegate = delegate;
    [self stopTimer];
    BOOL repeat = NO;
    _timer = [[NSTimer scheduledTimerWithTimeInterval:3 target:self selector:@selector(actionTimeUp:) userInfo:@{@"repeat":@(repeat)} repeats:repeat] retain];
}

- (void)resetDelegate{
    _delegate = nil;
}

@end
